import React from 'react'
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout";
import {connect,} from "react-redux"
import {withRouter} from 'react-router-dom'
import TabWithCustomUnderline from "../../layouts/TabWithCustomUnderline/TabWithCustomUnderline";
import LocalStorageService from "../../utils/LocalStorageService";
import AIGameCard from "../AI/AIGameCard/AIGameCard";
import './my-ai.css'
import GameAIModel from "../../model/GameAIModel";
import {formatDate, formatScheduleDate, getDifferenceBetweenDates} from "../../utils/dateService";
import DefaultTeamIcon from "../../res/images/web/shared/缺省头像.png";
import {ICON_URL_PREFIX} from "../../redux/game";
import GameAIItem from "../game-room/components/Main/index/GameAI/GameAIItem/GameAIItem";
import {bindEvent, getDom, getDoms} from "../../utils/commonfunc";
import _ from 'lodash'
import {Toast} from "antd-mobile";

class MyAi extends React.Component {
    constructor(props) {
        super(props)
        this.uid = LocalStorageService.get('userid')
        this.state = {
            type: 0,
            p: 0,
            p1: 0,
            end: false,
            end1: false,
        }
    }

    componentDidMount() {
        this.getList()
        this.bindScrollEvent()
    }

    bindScrollEvent = () => {
        const ctns = getDoms('.am-tabs-pane-wrap')

        if (ctns) {
            for (let i = 0; i < ctns.length; i++) {
                let ctn = ctns[i]
                const scrollCallback = _.throttle(() => {
                    const top = ctn.scrollTop
                    const hei = document.documentElement.clientHeight - 89
                    const scrollHei = ctn.scrollHeight
                    if ((top + hei) === scrollHei) {
                        if (this.state.type === 0) {
                            this.setState({
                                p: this.state.p + 1,
                            }, () => this.getList())
                        } else {
                            this.setState({
                                p1: this.state.p1 + 1,
                            }, () => this.getList())
                        }

                    }
                })
                bindEvent(ctn, 'scroll', scrollCallback)
            }

        }
    }

    getList = async () => {
        const type = this.state.type
        let p
        if (type === 0) {
            p = this.state.p
        } else if (type === 1) {
            p = this.state.p1
        }
        const uid = this.uid
        const end = this.state.end
        const end1 = this.state.end1
        if (type === 0 && end === true) {
            Toast.info('没有更多记录', 1)
            return
        }
        if (type === 1 && end1 === true) {
            Toast.info('没有更多记录', 1)
            return
        }
        const resp = await this.props.doGetMyAIList({type, params: {p, uid,}})
        const list = resp.ok
        if (list.length < 10) {
            if (type === 0) {
                this.setState({
                    end: true,
                })
            } else if (type === 1) {
                this.setState({
                    end1: true,
                })
            }
        }
    }

    onTabClick = (e, i) => {
        this.setState({
            type: i,
        }, () => {
            if (i === 0 && this.state.p === 0) {
                this.getList()
            } else if (i === 1 && this.state.p1 === 0) {
                this.getList()
            }

        })
    }

    render() {

        const history = this.props.history
        const type = this.state.type
        const tabs = [
            {title: '未赛',},
            {title: '已赛',},
        ]
        const data = this.props.game.myAI[type]
        let list = []
        Object.values(data).map(val => {
            if (val !== null) list.push(...val)
        })
        const listTemplate = list.map((game, index) => {


            const model = new GameAIModel(game)
            const detail = model.detail()
            const status = detail.status
            const schedule = detail.schedule
            const startAt = detail.startAt
            const homeTeam = detail.host
            const awayTeam = detail.away

            const isStarted = status >= 2 && status <= 8
            const isEarly = status === 1
            const isFirstHalf = status === 2
            const isHalfTime = status === 3
            const isSecondHalf = status === 4
            const isFinished = status === 8
            const isDelay = status >= 9

            const startAtTimeObj = new Date(startAt * 1000)
            const scheduleTimeObj = new Date(schedule * 1000)
            const scheduleDateString = formatDate(scheduleTimeObj)
            let scheduleDateFormat = scheduleDateString.slice(4, 6) + '月' + scheduleDateString.slice(6) + '日'
            const scheduleTimeString = formatScheduleDate(scheduleTimeObj)
            const now = new Date()
            const diff = getDifferenceBetweenDates(startAtTimeObj, now)
            const scheduleDiv = (<div className='my-ai-card-time-not-started'>
                <span>{scheduleDateFormat} {scheduleTimeString}</span>
            </div>)
            // console.log(pushDateString)
            let curTime
            if (isEarly) curTime = '未开赛'
            if (isFirstHalf) curTime = `上半场 ${diff.minutesDiff + 1}\'`
            if (isHalfTime) curTime = '半场 45\''
            if (isSecondHalf) curTime = `下半场 ${diff.minutesDiff + 45 + 1}\'`
            // const infoOffer = seasonInfo[3] === 1
            const curTimeTemplate = <span
                className='my-ai-card-cur-time '
            >{curTime}</span>

            const teamIcon = (team, home = true) => {
                const hostText = <div className='my-ai-card-team-text my-ai-card-team-text-h'>主</div>
                const awayText = <div className='my-ai-card-team-text my-ai-card-team-text-a'>客</div>
                // const {
                //     detail,
                // } = team
                const {
                    name,
                    logo,
                } = team
                const nameSpan = <span style={{textAlign: home ? 'right' : 'left',}}>{name}</span>
                return <div
                    className='AI-game-card-team-logo'
                    style={{
                        justifyContent: home ? 'flex-end' : 'flex-start',
                    }}
                >
                    {home ? nameSpan : null}
                    {home ? hostText : awayText}
                    <img
                        src={logo === '' ? DefaultTeamIcon : ICON_URL_PREFIX + logo}
                        alt=''
                    />
                    {home ? null : nameSpan}
                </div>
            }

            const homeScore = homeTeam.score
            const awayScore = awayTeam.score

            const score = <div className='AI-game-card-team-VS'>
                <span>{homeScore} : {awayScore}</span>
            </div>

            const vs = <div className='AI-game-card-team-VS AI-game-card-team-VS-not-started'>
                <span>-</span>
            </div>

            const competitionName = <span
                className='my-ai-card-c'
            >{detail.c}</span>

            const {style,} = game
            const RQ = model.RQ()
            const SFP = model.SFP()
            const DXQ = model.DXQ()
            const mapper = {
                1: RQ,
                2: SFP,
                3: DXQ,
            }
            const oddData = mapper[style]
            const AIItemData = {
                title: oddData.title,
                correct: oddData.result,
                type: style,
                data: {
                    home: oddData.home,
                    away: oddData.away,
                    tied: oddData.tied,
                    rateArr: oddData.oddsArr,
                },

            }

            return <div
                key={index}
                onClick={() => this.props.history.push(`../game/${detail.matchId}`)}
                style={{width: '100%',}}
            >
                <div className='my-ai-card-ctn'>
                    {competitionName}
                    {isStarted && !isFinished ? curTimeTemplate : scheduleDiv}
                    {teamIcon(homeTeam)}
                    {isStarted && !isDelay ? score : vs}
                    {teamIcon(awayTeam, false)}
                </div>
                <GameAIItem
                    AIItemData={AIItemData}
                    paid={true}
                    dataEmpty={false}
                    ctnStyle={{
                        backgroundColor: '#fff',
                    }}
                    status={detail.status}
                />
            </div>

            // return <AIGameCard game={game} key={index}/>
        })

        return (
            <GoBackLayout
                title='我购买的'
                history={history}
            >
                <div style={{marginTop: '1px',}}>
                    <TabWithCustomUnderline
                        tabs={tabs}
                        tabBarUnderlineStyle={{border: '2px #36C8B9 solid'}}
                        onTabClick={(e, i) => this.onTabClick(e, i)}
                    >

                        <div style={{
                            height: 'calc(100 * var(--vh) - 93.5px)',
                            width: '100%',
                        }}>
                            {listTemplate}
                        </div>


                    </TabWithCustomUnderline>
                </div>

            </GoBackLayout>
        )
    }
}

const mapState = state => ({
    game: state.game,
})

const mapDispatch = dispatch => ({
    doGetMyAIList: (payload) => dispatch.game.doGetMyAIList(payload),
})

export default connect(mapState, mapDispatch)(withRouter(MyAi))
